import 'dart:convert';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_levin/provider/token_store.dart';
import 'package:logger/logger.dart';

import '../storage_manager.dart';
import 'api.dart';

Http http = Http();

class Http extends BaseHttp {
  static const baseUrl = 'http://japitest.kaiwumace.com';

  @override
  void init() {
    options.baseUrl = baseUrl;
    interceptors
      ..add(ApiInterceptor())
      ..add(CookieManager(PersistCookieJar(storage: FileStorage(StorageManager.temporaryDirectory.path))));
  }
}

class ApiInterceptor extends InterceptorsWrapper {
  Logger logger = Logger();

  @override
  void onRequest(options,handler) {
    logger.d('token:${TokenStore.getToken()}');
    logger.d("request data----->${options.data}");
     super.onRequest(options,handler);
  }

  @override
  void onError( err,handler) {
     super.onError(err,handler);
  }

  @override
  void onResponse( response,handler) {
    var statusCode = response.statusCode;
    if (statusCode == 200) {
      if (response.data is Map) {
        RespData respData = RespData.fromJson(response.data);
        if (respData.success) {
          response.data = respData.data;
          handler.resolve(response);
          //return http.resolve(response);
        } else {
          handler.next(handleFailed(respData));
          //return handleFailed(respData);
        }
      } else {
        RespData apiResult = RespData.fromJson(jsonDecode(response.data));
        handler.next(handleFailed(apiResult));
        //return handleFailed(apiResult);
      }
    } else {
       handler.reject(DioError(requestOptions: response.requestOptions));
    }
    super.onResponse(response, handler);
  }

  Response handleFailed(RespData respData) {
    logger.e('---api-resp---->error------>$respData');
    if (respData.code == 2 || respData.code == 10) {
      throw const UnAuthorizedException();
    }
    throw NotSuccessException.fromRespData(respData);
    //return http.reject(respData.message);
  }
}

class RespData extends BaseRespData {
  @override
  bool get success => 1 == code;

  RespData.fromJson(Map<String, dynamic> map) {
    code = int.parse(map['code']);
    message = map['desc'];
    data = map['result'];
  }
}

_parseAndDecode(String resp) {
  return jsonDecode(resp);
}

parseJson(String text) {
  return compute(_parseAndDecode, text);
}
